<?php
/*
 +----------------------------------------------------------------------
 + Title        : ValidateParams 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2022/1/28 22:38
 + Last-time    : 2022/1/28 22:38+ chen2
 + Desc         : ValidateParams
 +----------------------------------------------------------------------
*/


namespace app\http\middleware;

use app\http\exception\BadRequestHttpException;
use app\Request;
use think\facade\App;
use think\facade\Cache;
use think\route\dispatch\Controller;

class ValidateParams
{
    /**
     * @throws \ReflectionException
     */
    public function handle(Request $request, \Closure $next)
    {
        $suffix = config('route.controller_suffix') ? 'Controller' : '';
        $controllerLayer = config('route.controller_layer') ?: 'controller';
        $class = App::parseClass($controllerLayer, $request->controller() . $suffix);

        $action = $request->action();

        $ref = new \ReflectionMethod($class, $action);
        $res = $ref->getAttributes();
        $params = \request()->post();

        $this->methodAttribute($res, $request->requestParams);
        $request->requestParams = $params;
        return $next($request);
    }



    //函数注解解析
    public function methodAttribute($attributes, &$params) : void
    {
        foreach ($attributes as $v) {
            $v->newInstance()
              ->run($params);
        }
    }


}